package com.zj.osm.adapter;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ToastUtils;
import com.flyco.dialog.widget.NormalDialog;
import com.zj.osm.App;
import com.zj.osm.R;
import com.zj.osm.entity.db.EquipmentDao;
import com.zj.osm.entity.db.LineDao;
import com.zj.osm.entity.db.OnlineDao;
import com.zj.osm.entity.db.PhotosDao;
import com.zj.osm.entity.db.PointDao;
import com.zj.osm.entity.db.ProjectDao;
import com.zj.osm.entity.greendao.Equipment;
import com.zj.osm.entity.greendao.Line;
import com.zj.osm.entity.greendao.Online;
import com.zj.osm.entity.greendao.Photos;
import com.zj.osm.entity.greendao.Point;
import com.zj.osm.entity.greendao.Project;
import com.zj.osm.utils.ExportUnit;
import com.zj.osm.view.home.home.home_fragment.onefragment.ProjectAdapterInterface;
import com.zj.osm.view.home.home.home_fragment.twofragment.page.LocalProjectFragment;
import com.zj.osm.view.navigation.NavigationActivity;
import com.zj.osm.view.project.projectdetail.ProjectDetailActivity;
import com.zj.utils.data.LiveDataBus;
import com.zj.utils.utils.TimeUtils;

import java.util.List;

import static com.blankj.utilcode.util.ActivityUtils.startActivity;
import static com.blankj.utilcode.util.FileUtils.deleteDir;
import static com.zj.osm.utils.Configuration.PROJECT_ID;
import static com.zj.osm.view.home.home.home_fragment.onefragment.OneFragment.DIALOG_BOTTOM;

/**
 * <pre>
 *     author : luhenchang
 *     e-mail : 1276998208@qq.com
 *     time   : 2019/12/03
 *     desc   : 版权所有
 *     version: 1.0
 * </pre>
 */
public class ProjectAdapter extends BaseAdapter {
    @SuppressLint("SdCardPath")
    private Context context;
    private List<Project> list;
    private boolean isCheck = true;
    private ProjectAdapterInterface projectAdapterInterface;
    public ProjectAdapter(Fragment fragment, List<Project> list) {
        this.context = fragment.getContext();
        this.list = list;
        projectAdapterInterface= (ProjectAdapterInterface) fragment;
    }
    public ProjectAdapter(Context context, List<Project> list,View interfaceObj) {
        this.context =context;
        this.list = list;
        projectAdapterInterface= (ProjectAdapterInterface) interfaceObj;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int position) {
        return list.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }


    /**
     * 删除设备对话框
     */
    public void startDialog(final int number, final long cid, final String name, final String state, final String type) {

        final NormalDialog dialog = new NormalDialog(context);
        dialog.content("您确定要删除吗?")//
                .style(NormalDialog.STYLE_TWO)//
                .btnNum(2)
                .title("删除设置")
                .btnText("取消", "删除")//
                .show();
        dialog.setOnBtnClickL(
                dialog::dismiss, () -> {
                    dialog.dismiss();
                    if (number == 1) {
                        if (deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                                + "/bhne/")) {
                            com.blankj.utilcode.util.ToastUtils.showShort("删除成功");
                        }
                    } else if (number == 2) {
                        deleteItem(cid, name);
                        /*if (state.equals("在线")) {
                            Online online = App.getInstances().getDaoSession().getOnlineDao().queryBuilder().where(OnlineDao.Properties.Id.eq(type)).list().get(0);
                            online.setDown("no");
                            App.getInstances().getDaoSession().getOnlineDao().update(online);
                            deleteItem(cid, name);
                        } else {
                            deleteItem(cid, name);
                        }*/
                        isCheck = false;
                        list = App.getInstances().getDaoSession().getProjectDao().queryBuilder().orderDesc(ProjectDao.Properties.Id).build().list();
                        notifyDataSetChanged();
                    }
                });
    }


    @SuppressLint("SetTextI18n")
    private void deleteItem(long cid, String name) {
        //删除所有相关联的数据
        App.getInstances().getDaoSession().getProjectDao().deleteByKey(cid);
        List<Point> PointList = App.getInstances().getDaoSession().getPointDao().queryBuilder().where(PointDao.Properties.ProjectId.eq(cid)).build().list();
        for (int j = 0; j < PointList.size(); j++) {
            App.getInstances().getDaoSession().getPointDao().delete(PointList.get(j));
            try {
                List<Equipment> equipmentList = App.getInstances().getDaoSession().getEquipmentDao().queryBuilder().where(EquipmentDao.Properties.PointId.eq(PointList.get(j).getId())).build().list();
                if (equipmentList.size() > 0)
                    for (int i = 0; i < equipmentList.size(); i++) {
                        App.getInstances().getDaoSession().getEquipmentDao().delete(equipmentList.get(i));
                    }
                List<Photos> photosList = App.getInstances().getDaoSession().getPhotosDao().queryBuilder().where(PhotosDao.Properties.Points_id.eq(PointList.get(j).getId())).build().list();
                if (photosList.size() > 0)
                    for (int i = 0; i < photosList.size(); i++) {
                        App.getInstances().getDaoSession().getPhotosDao().delete(photosList.get(i));
                    }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        List<Line> lines = App.getInstances().getDaoSession().getLineDao().queryBuilder().where(LineDao.Properties.Item_id.eq(cid)).build().list();
        try {
            for (int i = 0; i < lines.size(); i++) {
                App.getInstances().getDaoSession().getLineDao().delete(lines.get(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ToastUtils.showShort("删除成功");
        notifyDataSetChanged();
        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name);
        deleteDir(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/bhne/" + name + ".zip");
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint({"InflateParams", "SetTextI18n"})
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.activity_main_list, null);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else
            viewHolder = (ViewHolder) convertView.getTag();
        final Project items = list.get(position);
        if (!DIALOG_BOTTOM) {
            viewHolder.main_cb_switch.setVisibility(View.VISIBLE);
        } else {
            viewHolder.main_cb_switch.setVisibility(View.GONE);
        }
        if (items.getBatchCheck() == 1) {
            viewHolder.main_cb_switch.setChecked(true);
        } else {
            viewHolder.main_cb_switch.setChecked(false);
        }
        viewHolder.main_cb_switch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                items.setBatchCheck(1);
                App.getInstances().getDaoSession().getProjectDao().update(items);
            } else {
                items.setBatchCheck(0);
                App.getInstances().getDaoSession().getProjectDao().update(items);
            }
        });
        if (items.getName().length()>9){
            viewHolder.main_tv_name.setText(items.getName());//大于八个字符显示省略号
        }else {
            viewHolder.main_tv_name.setText(items.getName());//设置标题为当前项目名称
        }

        //viewHolder.main_tv_name.setText(items.getName() + "");
        viewHolder.main_tv_note.setText(items.getType() + "  " + items.getVoltage());
        viewHolder.main_tv_time.setText(items.getTime() + "");
        ExportUnit exportUnit = new ExportUnit(context,items.getId(), items.getName());
        if ("在线".equals(items.getState())) {
            viewHolder.main_iv.setBackgroundResource(R.drawable.img_zaixian);
            viewHolder.main_tv_upload.setOnClickListener(v13 -> exportUnit.SetLocalExport());
            viewHolder.main_tv_up.setVisibility(View.VISIBLE);
            //viewHolder.main_tv_up.setOnClickListener(view -> );
            viewHolder.main_tv_up.setOnClickListener(v -> exportUnit.SetExport());
        } else {
            viewHolder.main_iv.setBackgroundResource(R.drawable.img_bendi);
            viewHolder.main_tv_upload.setOnClickListener(v13 ->{
                /**
                 *
                 */
                //exportUnit.getXmlFile();
                //exportUnit.getZipFile();

                exportUnit.generateExcle();

            } /*exportUnit.SetLocalExport()*/);
            viewHolder.main_tv_up.setVisibility(View.GONE);
        }
        viewHolder.main_navi.setOnClickListener(v -> {
            LiveDataBus.get().getChannel(PROJECT_ID).setValue(items.getId());
            Intent intent = new Intent(context, NavigationActivity.class);
            startActivity(intent);
        });

        /**
         * 2019年12月11日
         */
        viewHolder.main_ibt_details.setImageResource(R.drawable.xialas);
        viewHolder.bellow_layout.setVisibility(View.VISIBLE);
        viewHolder.main_tv_details.setOnClickListener(v1 -> {
            if (items.getIsCheck()) {
                Intent intent = new Intent(context,ProjectDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putLong(PROJECT_ID, items.getId());
                intent.putExtra("intent_bundle", bundle);
                startActivity(intent);
            } else {
                /*Intent intent = new Intent(context, OnlineDetailsActivity.class);
                intent.putExtra("details", items.getId());
                intent.putExtra("de_id", 2);
                context.startActivity(intent);*/
            }

        });
        viewHolder.main_tv_delete.setOnClickListener(v12 -> startDialog(2, items.getId(), items.getName(), items.getState(), items.getType()));



        viewHolder.main_ibt_details.setOnClickListener(v -> {
            if (isCheck) {
                viewHolder.main_ibt_details.setImageResource(R.drawable.xialas);
                viewHolder.bellow_layout.setVisibility(View.VISIBLE);
                viewHolder.main_tv_details.setOnClickListener(v1 -> {
                    if (items.getIsCheck()) {
                        Intent intent = new Intent(context,ProjectDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putLong(PROJECT_ID, items.getId());
                        intent.putExtra("intent_bundle", bundle);
                        startActivity(intent);
                    } else {
                       /* Intent intent = new Intent(context, OnlineDetailsActivity.class);
                        intent.putExtra("details", items.getId());
                        intent.putExtra("de_id", 2);
                        context.startActivity(intent);*/
                    }

                });
                viewHolder.main_tv_delete.setOnClickListener(v12 -> startDialog(2, items.getId(), items.getName(), items.getState(), items.getType()));
                isCheck = !isCheck;
            } else {
                viewHolder.main_ibt_details.setImageResource(R.drawable.jinru);
                viewHolder.bellow_layout.setVisibility(View.VISIBLE);
                isCheck = !isCheck;
            }
        });
        return convertView;
    }


    class ViewHolder {
        private TextView main_tv_name;
        private TextView main_tv_note;
        private ImageButton main_ibt_details;
        private TextView main_tv_time;
        private RelativeLayout bellow_layout;
        private TextView main_tv_upload;
        private TextView main_tv_up;
        private TextView main_tv_delete;
        private TextView main_tv_details;
        private CheckBox main_cb_switch;
        private ImageView main_iv;
        private ImageView main_navi;

        ViewHolder(View rootView) {
            this.main_tv_name = rootView.findViewById(R.id.main_tv_name);
            this.main_tv_note = rootView.findViewById(R.id.main_tv_note);
            this.main_ibt_details = rootView.findViewById(R.id.main_ibt_details);
            this.main_tv_time = rootView.findViewById(R.id.main_tv_time);
            this.bellow_layout = rootView.findViewById(R.id.below_layout);
            this.main_tv_upload = rootView.findViewById(R.id.main_tv_upload);
            this.main_tv_up = rootView.findViewById(R.id.main_tv_up);
            this.main_tv_delete = rootView.findViewById(R.id.main_tv_delete);
            this.main_tv_details = rootView.findViewById(R.id.main_tv_details);
            this.main_cb_switch = rootView.findViewById(R.id.main_cb_switch);
            this.main_iv = rootView.findViewById(R.id.main_iv);
            this.main_navi = rootView.findViewById(R.id.main_navi);

        }

    }

}
